package com.xincongjun.media.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.stream.Collectors;

import static com.xincongjun.media.utils.FileUtil.*;

public class FFmpegUtil {

    private static final Logger logger = LoggerFactory.getLogger(FFmpegUtil.class);

    public static void useFFmpegConvertFileType(File file, String targetFileType) throws Exception {
        String filePath = file.getAbsolutePath();
        String newFilePath = filePath.substring(0, filePath.lastIndexOf(".")) + "_original" + "." + targetFileType;

        ProcessBuilder builder = new ProcessBuilder(
                "ffmpeg", "-i", filePath, newFilePath
        );
        builder.redirectErrorStream(true);

        try {
            Process process = builder.start();

            String output;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")))) {
                output = reader.lines().collect(Collectors.joining(System.lineSeparator()));
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("执行 FFmpeg 命令失败：" + filePath + "\n" + output);
            }else {
                swapFileNames(filePath, newFilePath);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
